package com.boss.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import com.boss.model.Person;

public class PersonDao {
	public JdbcTemplate jdbcTemplate;

	public static final String TABLE_NAME="person";
	
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	private static class PersonRowMapper implements RowMapper {
		public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
			Person person = new Person(null);
			try {
				person.setId(Integer.parseInt(rs.getString("ID")));
			} catch (Exception e) {
				e.printStackTrace();
			}
			person.setName(rs.getString("NAME"));
			return person;
		}
	}
	public Person get(){
		return new Person("zoey");
	}
	public int save(Person person) {
		String sql = "insert into "+TABLE_NAME+"(ID,NAME) values ("+person.getId()+","+person.getName()+")";
		return jdbcTemplate.update(sql);
	}
	public int delete(Person person) {
		String sql = "delete from "+TABLE_NAME+" where ID=" + person.getId();
		return jdbcTemplate.update(sql);
	}
	public int update(Person person) {
		String sql = "update " + TABLE_NAME + " set NAME='update_name' where ID=" + person.getId();
		return jdbcTemplate.update(sql);
	}
	public Person getById(int id) {
		String sql="select * from "+TABLE_NAME+"   where ID="+id;
		List<Person> list = jdbcTemplate.query(sql,new PersonRowMapper());
		return list.get(0);
	}
}
